<template>
  <div class="order-confirmation-page">
    <div class="container">
      <h1>订单确认</h1>

      <!-- 商品信息 -->
      <div class="section">
        <h2>商品信息</h2>
        <div class="table-container">
          <el-table :data="orderItems" border style="width: 100%">
            <el-table-column prop="name" label="商品信息" width="300">
              <template #default="scope">
                <div class="product-info">
                  <img 
                    :src="getProductImage(scope.row)" 
                    :alt="scope.row.name" 
                    class="product-image"
                    @error="handleImageError"
                  />
                  <div class="product-details">
                    <div class="product-name">{{ scope.row.name }}</div>
                  </div>
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="price" label="单价" width="120">
              <template #default="scope">
                ￥{{ scope.row.price }}
              </template>
            </el-table-column>
            <el-table-column prop="quantity" label="数量" width="100" />
            <el-table-column prop="subtotal" label="小计" width="120">
              <template #default="scope">
                ￥{{ (scope.row.price * scope.row.quantity).toFixed(2) }}
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>

      <!-- 收货地址 -->
      <div class="section">
        <h2>收货地址</h2>
        <div class="address-list">
          <div
              v-for="address in addresses"
              :key="address.id"
              class="address-item"
              :class="{ 'selected': selectedAddress && selectedAddress.id === address.id }"
              @click="selectAddress(address)"
          >
            <div class="address-info">
              <div class="address-name">收货人：{{ address.receiveName }}</div>
              <div class="address-mobile">手机号：{{ address.mobile }}</div>
              <div class="address-detail">地址：{{ address.address }}</div>
            </div>
            <div class="address-default" v-if="address.isDefault === 1 || address.isDefault === true">默认地址</div>
          </div>
          <div class="address-item add-new" @click="showAddressForm = true">
            <div class="add-icon">+</div>
            <div>添加新地址</div>
          </div>
        </div>
      </div>
      
      <!-- 订单总计 -->
      <div class="section order-summary">
        <h2>订单总计</h2>
        <div class="summary-item">
          <span>商品总价：</span>
          <span>￥{{ totalAmount }}</span>
        </div>
        <div class="summary-item">
          <span>运费：</span>
          <span>￥{{ shippingFee.toFixed(2) }}</span>
        </div>
        <div class="summary-item total">
          <span>应付总额：</span>
          <span>￥{{ (parseFloat(totalAmount) + shippingFee).toFixed(2) }}</span>
        </div>
      </div>
      
      <!-- 提交订单 -->
      <div class="section">
        <el-button type="primary" @click="submitOrder" :loading="isSubmitting">提交订单</el-button>
      </div>
    </div>
    
    <!-- 地址表单弹窗 -->
    <el-dialog v-model="showAddressForm" title="添加收货地址" width="500px">
      <el-form :model="addressForm" :rules="addressRules" ref="addressFormRef">
        <el-form-item label="收货人" prop="receiveName">
          <el-input v-model="addressForm.receiveName" />
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="addressForm.mobile" />
        </el-form-item>
        <el-form-item label="详细地址" prop="address">
          <el-input v-model="addressForm.address" type="textarea" />
        </el-form-item>
        <el-form-item label="设为默认地址" prop="isDefault">
          <el-switch v-model="addressForm.isDefault" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showAddressForm = false">取消</el-button>
        <el-button type="primary" @click="saveAddress">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { getAddressList, addAddress } from '@/api/addressApi'
import { createOrder } from '@/api/orderApi'

export default {
  name: 'OrderConfirmation',
  data() {
    return {
      addresses: [],
      selectedAddress: null,
      orderItems: [],
      totalAmount: '0.00',
      shippingFee: 0.00,
      showAddressForm: false,
      isSubmitting: false,
      addressForm: {
        receiveName: '',
        mobile: '',
        address: '',
        isDefault: false
      },
      addressRules: {
        receiveName: [
          { required: true, message: '请输入收货人姓名', trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { pattern: /^1[3-9]\d{9}$/, message: '手机号格式不正确', trigger: 'blur' }
        ],
        address: [
          { required: true, message: '请输入详细地址', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    // 从路由参数获取购物车数据
    const cartItems = JSON.parse(this.$route.params.cartItems || '[]')
    this.totalAmount = this.$route.params.totalAmount || '0.00'
    
    // 转换购物车数据为订单项
    this.orderItems = cartItems.map(item => ({
      ...item,
      subtotal: (item.price * item.quantity).toFixed(2)
    }))
    
    // 获取用户地址列表
    this.fetchAddresses()
  },
  methods: {
    // 获取用户地址列表
    async fetchAddresses() {
      try {
        const response = await getAddressList()
        // 修复：正确处理响应数据，与地址管理组件保持一致
        this.addresses = response || []
        // 设置默认选中地址
        this.selectedAddress = this.addresses.find(addr => addr.isDefault === 1 || addr.isDefault === true) || this.addresses[0] || null
      } catch (error) {
        console.error('获取地址列表失败:', error)
        this.$message.error('获取地址列表失败: ' + (error.message || '网络错误'))
      }
    },
    
    // 选择地址
    selectAddress(address) {
      this.selectedAddress = address
    },
    
    // 获取商品图片
    getProductImage(product) {
      if (product.image) {
        try {
          return require(`@/assets/files/${product.image}`)
        } catch (error) {
          console.warn(`商品图片加载失败: ${product.image}`, error)
          return require('@/assets/images/default_product.jpg')
        }
      }
      return require('@/assets/images/default_product.jpg')
    },
    
    // 图片加载错误处理
    handleImageError(event) {
      event.target.src = require('@/assets/images/default_product.jpg')
    },
    
    // 保存地址
    async saveAddress() {
      try {
        const response = await addAddress(this.addressForm)
        if (response.status === 200) {
          this.$message.success('地址添加成功')
          this.showAddressForm = false
          this.resetAddressForm()
          // 重新获取地址列表
          await this.fetchAddresses()
        } else {
          this.$message.error(response.message || '地址添加失败')
        }
      } catch (error) {
        console.error('地址添加失败:', error)
        this.$message.error('地址添加失败: ' + (error.message || '网络错误'))
      }
    },
    
    // 重置地址表单
    resetAddressForm() {
      this.addressForm = {
        receiveName: '',
        mobile: '',
        address: '',
        isDefault: false
      }
    },
    
    // 提交订单
    async submitOrder() {
      // 检查是否选择了地址
      if (!this.selectedAddress) {
        this.$message.warning('请选择收货地址')
        return
      }
      
      // 准备订单数据
      const orderData = {
        address: this.selectedAddress.id,
        products: this.orderItems.map(item => ({
          productId: item.id,
          quantity: item.quantity
        }))
      }
      
      try {
        this.isSubmitting = true
        const response = await createOrder(orderData)
        // 修改判断条件，兼容处理success字符串响应
        if (response.status === 200 || response === "success" || (typeof response === 'string' && response.startsWith('success'))) {
          this.$message.success('订单提交成功')
          // 跳转到订单详情页面，需要从响应中提取订单ID
          let orderId = null;
          if (response.data && response.data.id) {
            orderId = response.data.id;
          } else if (response.data && response.data.serialNumber) {
            // 从新的数据格式中提取订单号
            orderId = response.data.serialNumber;
          } else if (typeof response === 'string' && response.startsWith('success:')) {
            // 从"success:订单ID"格式中提取订单ID（处理可能存在的空格）
            orderId = response.split(':')[1].trim(); // 使用trim()去除可能的空格
          }
          
          if (orderId) {
            this.$router.push({
              name: 'AlipayPayment',
              params: { 
                orderId: orderId,
                amount: (parseFloat(this.totalAmount) + this.shippingFee).toFixed(2)
              }
            })
          }
          // 删除无法提取订单号时跳转到订单管理页面的逻辑
        } else {
          this.$message.error(response.message || '订单提交失败')
        }
      } catch (error) {
        console.error('订单提交失败:', error)
        this.$message.error('订单提交失败: ' + (error.message || '网络错误'))
      } finally {
        this.isSubmitting = false
      }
    }
  }
}
</script>

<style scoped>
.order-confirmation-page {
  padding: 20px;
}

.container {
  max-width: 1200px;
  margin: 0 auto;
}

.section {
  margin-bottom: 30px;
  padding: 20px;
  border: 1px solid #eee;
  border-radius: 4px;
  background-color: #fff;
}

.section h2 {
  margin-top: 0;
  margin-bottom: 20px;
  color: #333;
}

/* 地址列表样式 */
.address-list {
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
}

.address-item {
  flex: 1;
  min-width: 250px;
  padding: 15px;
  border: 1px solid #ddd;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s;
}

.address-item:hover {
  border-color: #409eff;
}

.address-item.selected {
  border-color: #409eff;
  background-color: #ecf5ff;
}

.address-info .address-name {
  font-weight: bold;
  margin-bottom: 5px;
}

.address-info .address-mobile {
  color: #666;
  margin-bottom: 5px;
}

.address-info .address-detail {
  color: #999;
}

.address-default {
  display: inline-block;
  padding: 2px 5px;
  font-size: 12px;
  color: #fff;
  background-color: #ff4e00;
  border-radius: 2px;
  margin-top: 10px;
}

.address-item.add-new {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: #999;
  border-style: dashed;
}

.add-icon {
  font-size: 24px;
  font-weight: bold;
  margin-bottom: 5px;
}

/* 商品信息样式 */
.product-info {
  display: flex;
  align-items: center;
}

.product-image {
  width: 80px;
  height: 80px;
  object-fit: cover;
  margin-right: 15px;
  border-radius: 4px;
}

.product-details {
  flex: 1;
}

.product-name {
  font-weight: bold;
  margin-bottom: 5px;
}

/* 订单总计样式 */
.order-summary {
  background-color: #f9f9f9;
}

.summary-item {
  display: flex;
  justify-content: space-between;
  padding: 10px 0;
  border-bottom: 1px solid #eee;
}

.summary-item.total {
  font-weight: bold;
  font-size: 18px;
  color: #ff4e00;
  border-bottom: none;
}
.table-container {
  margin: 0 !important;
}

/* 彻底解决el-table样式被全局样式覆盖的问题 */
.table-container :deep(.el-table) {
  margin: 0 !important;
  width: 100% !important;
}

.table-container :deep(.el-table__header-wrapper) {
  margin: 0 !important;
}

.table-container :deep(.el-table__header) {
  margin: 0 !important;
  width: 100% !important;
  table-layout: fixed !important;
  border-collapse: separate !important;
}

.table-container :deep(.el-table__body-wrapper) {
  margin: 0 !important;
}

.table-container :deep(.el-table__body) {
  margin: 0 !important;
  width: 100% !important;
  table-layout: fixed !important;
  border-collapse: separate !important;
}

.table-container :deep(table) {
  margin: 0 !important;
  border-collapse: separate !important;
  table-layout: fixed !important;
}
</style>